import React, { Component } from "react";
import { Modal, Button, Form, InputNumber, DatePicker, Row, Col, Select, Input, Space, Tooltip } from 'antd';
import { QuestionCircleOutlined } from "@ant-design/icons"
import GoBack from "@/components/TheGoBack";
import TheTable from "@/components/TheTable"
import TheButton from "@/components/TheButton";
import "../style/style.less";
import { getHotelOrderDetail } from "../../../../request/hotelOrder";
import { apiGetHotelOrderDetail, apiPostHotelOrderDirectRefund } from "@/request/hotel";
import _ from "lodash";

const { confirm } = Modal;
const { TextArea } = Input
const { Option } = Select
export default class detials extends Component {
  constructor() {
    super()
    this.formRef = React.createRef()
    this.bindPetFormRef = React.createRef()
    this.state = {
      columnsHouse: [
        {
          title: "房间名称",
          dataIndex: "serviceName",
          key: "serviceName",
        },
        {
          title: "房间号码",
          dataIndex: "roomName",
          key: "roomName",
        },
        {
          title: "房间价格",
          dataIndex: "serviceRealPrice",
          key: "serviceRealPrice",
          render: (text, render) => {
            return <React.$Price price={render.serviceRealPrice} />
          }
        },
        {
          title: "入住日期",
          dataIndex: "beginTime",
          key: "beginTime",
        },
        {
          title: "离店日期",
          dataIndex: "endTime",
          key: "endTime",
        },
        {
          title: "入住天数",
          dataIndex: "daysNum",
          key: "daysNum",
        },
        // {
        //   title: "操作",
        //   render: (text, record ) => {
        //     return (
        //         // record.orderState === '1' ? <TheButton onClick={() => this.cancelOrder(record.hotelOrderId, record.orderState)}>取消订单</TheButton> : ''
        //         <TheButton onClick={() => this.applyRefund(record)}>申请退款</TheButton>

        //       // <TheButton onClick={() => this.cancelOrder(record.id, record.type)}>取消订单</TheButton>
        //     )
        //   },
        // }
      ],
      dataSourceHouse: [], //房间数据
      columnsCost: [
        {
          title: "房间名称",
          dataIndex: "serviceName",
          key: "serviceName",
        },
        {
          title: "房间号码",
          dataIndex: "roomName",
          key: "roomName",
        },
        {
          title: "房间价格",
          dataIndex: "serviceRealPrice",
          key: "serviceRealPrice",
          render: (text, render) => {
            return <React.$Price price={render.serviceRealPrice} />
          }
        },
        {
          title: "入住日期",
          dataIndex: "oneInday",
          key: "oneInday",
        },
        {
          title: "离店日期",
          dataIndex: "oneOutDay",
          key: "oneOutDay",
        },
        {
          title: "入住天数",
          dataIndex: "whetherCheckIn",
          key: "whetherCheckIn",
        }
      ],
      dataSourceCost: [], //费用数据
      petData_1: [], // 宠物信息
      petData_2: [], // 宠物信息
      type: 10,
      status: 'Y',
      orderData: [], // 订单信息
      isModalVisible: false,
      data: {},
      refund: false,
      totalPrice: '',
      onlinePrice: '',
      cash: '',
      initialValues: {
        reason: "与商家协商一致退款",
        memberCouponList: []
      },
      hide: false,
      memberCouponList: []
    }

  }
  componentDidMount() {
    this.getData()
  }
  // 订单详情列表
  getData = async () => {
    let hotelOrderId = ''
    if (this.props.match) {
      hotelOrderId = this.props.match.params.id
    }
    else {
      hotelOrderId = this.props.id
      this.setState({
        hide: true
      })
    }
    let res = await getHotelOrderDetail({ hotelOrderId: hotelOrderId })
    if (res.code === 0) {
      const data = res.data
      // 订单状态
      let orderStatus = ''
      switch (data.orderState) {
        case '0':
          orderStatus = '已结束'
          break
        case '1':
          orderStatus = '待付款'
          break
        case '2':
          orderStatus = '待入住'
          break
        case '3':
          orderStatus = '已入住'
          break
        case '4':
          orderStatus = '已取消'
          break
        case '9':
          orderStatus = '交易成功'
          break

      }
      // 支付方式
      let payWay = ''
      switch (data.payWay) {
        case 'WeChat':
          payWay = '微信'
          break;
        case 'Alipay':
          payWay = '支付宝'
          break;
        case 'UnionPay':
          payWay = "银联"
          break;
        case 'YsPay':
          payWay = "银行卡支付"
          break;
        case 'Cash':
          payWay = "现金"
          break;
        case 'Wallet':
          payWay = "余额"
          break;
        case 'Fix':
          payWay = "混合支付"
          break;
        case 'RemoteAlipay':
          payWay = "扫码支付（支付宝）"
          break;
        case 'RemoteWeChat':
          payWay = "扫码支付（微信）"
          break;
        default:
          payWay = "未知支付方式"
      }
      // 宠物性别
      const petData_1 = [
        {
          title: "宠主姓名",
          value: data.nickName,
        },
        {
          title: "手机号码",
          value: data.memberMobile,
        },
      ]
      const petData_2 = [
        {
          title: "宠物信息",
          value: data.petName,
        },
        {
          title: "宠物品种",
          value: data.petVarieties,
        },
        {
          title: "宠物生日",
          value: data.birthday,
        },
        {
          title: "宠物性别",
          value: data.petSex == 1 ? '公' : '母',
        },
        {
          title: "绝育信息",
          value: data.sterilizationStatus === 'Y' ? '已绝育' : '未绝育',
        },
        {
          title: "疫苗信息",
          value: data.vaccineStatus === 'Y' ? '已接种' : '未接种',
        }
      ]
      let orderData = [
        {
          title: "订单编号",
          value: data.orderCode,
        },
        {
          title: "订单来源",
          value: data.isOffLine === 0 ? "哈奇马APP预订" : data.isOffLine === 1 ? "酒店收银台" : '微信小程序'
        },
        {
          title: "订单状态",
          value: orderStatus
        },
        {
          title: "支付方式",
          value: payWay,
        },
        {
          title: "下单日期",
          value: data.createTime,
        },
        {
          title: "入住日期",
          value: data.checkInTime,
        },
      ]
      if (data.payWay === 'Fix') {
        let newOrderData = JSON.parse(JSON.stringify(orderData))
        let paylist = []
        data.payInfoList.map(item => {
          let payWay = ''
          switch (item.payWay) {
            case 'WeChat':
              payWay = '微信'
              break;
            case 'Alipay':
              payWay = '支付宝'
              break;
            case 'UnionPay':
              payWay = "银联"
              break;
            case 'YsPay':
              payWay = "银行卡支付"
              break;
            case 'Cash':
              payWay = "现金"
              break;
            case 'Wallet':
              payWay = "余额"
              break;
            case 'Fix':
              payWay = "混合支付"
              break;
            case 'RemoteAlipay':
              payWay = "扫码支付（支付宝）"
              break;
            case 'RemoteWeChat':
              payWay = "扫码支付（微信）"
              break;
            default:
              payWay = "未知支付方式"
          }
          paylist.push({
            title: payWay,
            value: (item.payPrice / 100).toFixed(2)
          })
        })
        newOrderData.splice(4, 0, paylist)
        orderData = _.flatten(newOrderData)
      }
      this.setState({
        petData_1,
        petData_2,
        orderData,
        dataSourceHouse: [data],
        dataSourceCost: data.hotelOrderGetDetailListVoList,
        data
      });
    }
  }
  // 申请退款
  applyRefund = (e) => {
    console.log(e)
    this.setState({
      isModalVisible: true,

    })
  }
  // 取消订单
  cancelOrder = (id, type) => {
    console.log(id, type);
  }
  // 确认取消
  handleOk = () => {
    console.log('确定')
  }
  // 不取消
  handleCancel = () => {
    console.log('取消')
  }
  onChange = (value, dateString) => {
    console.log('Selected Time: ', value);
    console.log('Formatted Selected Time: ', dateString);
  };
  onOk = (value) => {
    console.log('onOk: ', value);
  };
  reset() {
    setTimeout(() => {
      this.formRef.current.resetFields();
    }, 1000)
  }
  // 退款
  openDirectRefund = async () => {
    let hotelOrderId = this.props.match.params.id
    let res = await apiGetHotelOrderDetail({ hotelOrderId })
    let onlinePrice, cash
    if (res.code === 0) {
      cash = res.data.cashPrice ? React.$transNum(res.data.cashPrice, 2, -2) : '0.00'
      onlinePrice = (React.$transNum(res.data.orderPayPrice, 2, -2) - cash).toFixed(2)
    }
    console.log(onlinePrice);
    this.setState({
      isModalVisible: true,
      onlinePrice,
      totalPrice: React.$transNum(res.data.orderPayPrice, 2, -2),
      cash
    })
  }
  onCancel = () => {
    this.setState({
      isModalVisible: false,
      loading: false
    })
  }
  directRefund = async () => {
    let hotelOrderId = this.props.match.params.id
    let values = this.bindPetFormRef.getFieldsValue()
    values.hotelOrderId = hotelOrderId
    values.returnPrice = (values.returnPrice * 100).toFixed(0)
    let res = await apiPostHotelOrderDirectRefund({ ...values })
    if (res.code === 0) {
      React.$message({
        type: 'success',
        content: '退款成功！'
      })
      this.onCancel()
      this.getData()
    }
  }
  render() {
    const { dataSourceHouse, data, loading, totalPrice, cash, onlinePrice, initialValues, columnsHouse, dataSourceCost, columnsCost, orderData, petData_1, petData_2, isModalVisible, hide } = this.state
    let price = dataSourceHouse.orderPayPrice
    return (
      <>
        <div className="users-details" style={{ position: "relative" }}>
          {hide ? "" : <GoBack history={this.props.history} title={'订单信息'} />}
          {
            hide ? null : <div style={{ position: "absolute", top: '20px', right: '20px' }} >
              {['2', '3'].includes(data.orderState) && <TheButton
                // hasPermi={['hotel:order:refund']}
                type="primary" size="middle" onClick={this.openDirectRefund} >退款</TheButton>}
            </div>
          }

          <div className="order_info">
            {/* <div className="title">订单信息</div> */}
            <div className="order_content">
              {orderData.map((v, i) => {
                return (
                  <div key={i}>
                    <span>{v.title}:</span>
                    <span>{v.value}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
        <div className="users-details">
          <div className="order_info">
            <div className="order_content">
              {petData_1.map((v, i) => {
                return (
                  <div key={i}>
                    <span>{v.title}:</span>
                    <span>{v.value}</span>
                  </div>
                );
              })}
            </div>
            <div className="order_content">
              {petData_2.map((v, i) => {
                return (
                  <div key={i}>
                    <span>{v.title}:</span>
                    <span>{v.value}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
        <div className="users-details " style={{ marginTop: 20 }}>
          <div style={{ margin: "10px 0", fontSize: 16, fontWeight: 600 }}>房间信息</div>
          <TheTable
            style={{ marginBottom: 20 }}
            columns={columnsHouse}
            dataSource={dataSourceHouse}
          />
          {/* {
            <Modal title='申请退款' visible={isModalVisible} width="30%"
              onCancel={
                () => {
                  this.reset()
                  this.setState({ isModalVisible: false })
                }
              }
              footer={null}
            >
              <Form
                ref={this.formRef}
                onFinish={(values) => this.onFinish(values)}
                labelAlign='left'
              >
                <Form.Item style={{ marginBottom: 10 }} label="办理退房房间" name='name' >{}</Form.Item>
                <Form.Item style={{ marginBottom: 10 }} label="原计划入住离开时间" name='name' >
                  2022-12-28-2022-12-31&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;共7天6晚
                </Form.Item>
                <Form.Item style={{ marginBottom: 10 }} label="实际入住时间" name='name' >
                  2022-12-28-2022-12-31
                </Form.Item>
                <Form.Item style={{ marginBottom: 10 }} label="实际离开时间" name='aaa' >
                  <DatePicker showTime onChange={this.onChange} onOk={this.onOk} />
                  &nbsp;&nbsp;&nbsp;共7天6晚
                </Form.Item>
                <Form.Item style={{ marginBottom: 10 }} label="费用明细" name='name' >
                </Form.Item>
                <Form.Item style={{ marginBottom: 10 }}>
                  <Row >
                    <Col span={10}>
                      <Form.Item style={{ marginBottom: 10 }}
                        name="captcha"
                        label="用户实际支付费用"
                      >
                        ￥899
                      </Form.Item>
                    </Col>
                    <Col span={12} >
                      <Form.Item style={{ marginBottom: 10, color: 'red' }}
                        name="captcha"
                        label="系统自动计算可退费用"
                      >
                        ￥399
                      </Form.Item>
                    </Col>
                  </Row>
                </Form.Item>
                <Form.Item
                  style={{ marginBottom: 10 }}
                  name="captcha"
                  label="退款金额"
                  wrapperCol={{
                    span: 12,
                  }}
                >
                  <InputNumber placeholder="请输入需要退款的金额" />
                </Form.Item>
                <Form.Item
                  style={{ marginBottom: 10 }}
                  name="captcha"
                  label="退款原因"
                  wrapperCol={{
                    span: 12,
                  }}
                >
                  <Select placeholder="请选择" />
                </Form.Item>
                <Form.Item
                  style={{ marginBottom: 10 }}
                  name="captcha"
                >
                  <TextArea rows={4} placeholder="选填(补充详细退款原因)" maxLength={200} />
                </Form.Item>
                <div style={{ color: '#9d9d9d' }}>备注:系统预计1个工作日完成相关退款</div>
                <Form.Item
                  style={{ marginTop: 20, }}
                  wrapperCol={{
                    offset: 8,
                    span: 16,
                  }}>
                  <Button style={{ width: 100 }} type="primary" htmlType="submit">
                    同意退款
                  </Button>
                </Form.Item>
              </Form>
            </Modal>
          } */}
          <div style={{ margin: "10px 0", fontSize: 16, fontWeight: 600 }}>费用信息</div>
          <TheTable
            columns={columnsCost}
            dataSource={dataSourceCost}
          />

          <div className="foot_content users-details ">
            <div style={{ marginLeft: 30 }}>共计入住:&nbsp;
              {`${data.daysNum + 1}天${data.daysNum}晚`}
              {/* {data.daysNum === 1 ? data.daysNum + '天 ' : data.daysNum + '天' + `${data.daysNum+1} 晚`} */}
            </div>
            <div style={{ marginLeft: 30 }}>费用总计:&nbsp;
              <React.$price price={data.orderTotalPrice} />
            </div>
            <div style={{ marginLeft: 30 }}>优惠券抵扣:&nbsp;
            {data.couponTotal ? <><React.$price price={data.couponTotal} />&nbsp;
              {data.memberCouponInfoCouponCountVos && data.memberCouponInfoCouponCountVos.length > 0 ? <Tooltip title={data.memberCouponInfoCouponCountVos.map((res) => {
                  return <p>{res.memberCoupon.couponTitle + " X " + res.count}</p>
                })}><QuestionCircleOutlined /> </Tooltip> : <></>
              }</> : <React.$price price={data.couponTotal} />
            }
            </div>
            <div style={{ marginLeft: 30 }}>实际支付:&nbsp;
              <React.$price price={data.orderPayPrice} />
            </div>
          </div>
          {/* <div className="users-details btn">
            <TheButton size="middle" type="primary">查看监控</TheButton>
          </div> */}
        </div>
        <Modal
          title="退款"
          footer={null}
          width={'40%'}
          visible={isModalVisible}
          onCancel={this.onCancel}
        >
          <Form
            ref={ref => this.bindPetFormRef = ref} onFinish={this.directRefund}
            labelAlign="right"
            labelCol={{ span: 4, offset: 0 }}
            wrapperCol={{ span: 12, offset: 0 }}
            initialValues={initialValues}
          >
            <Form.Item label="退款原因" name={'reason'} rules={[{ required: true }]} >
              <Select >
                <Option value="与商家协商一致退款">与商家协商一致退款</Option>
                <Option value="不想要了">不想要了</Option>
                <Option value="选错了">选错了</Option>
              </Select>
            </Form.Item>
            <Form.Item label="实付金额">
              <div>￥{totalPrice}（其中现金支付：￥{cash}）</div>
            </Form.Item>
            <Form.Item label="退款金额" >
              <Row gutter={8}>
                <Col span={18}>
                  <Form.Item
                    name="returnPrice"
                    noStyle
                    rules={[
                      {
                        required: true,
                        message: `请输入0.01~${totalPrice - cash}范围内的金额！`,
                      },
                    ]}
                  >
                    <InputNumber />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  元
                </Col>
              </Row>
            </Form.Item>
            <div style={{ position: "relative", marginLeft: '100px', marginTop: '-10px' }} >其中<span style={{ color: '#D9001B' }}>￥{onlinePrice}</span>可原路返回，<span style={{ color: '#D9001B' }} >￥{cash}</span>需要线下手动退还现金</div>
            <Form.Item label="退款方式">
              <div>原路返回</div>
            </Form.Item>
            <Form.Item label="优惠券退还" name="memberCouponIds" >
              <Select mode="tags" >
                {data.memberCouponList && 
                  data.memberCouponList.map(res=>{
                    return <Option value={res.memberCouponId} >{res.couponTitle}</Option>
                  })
                }
              </Select>
            </Form.Item>
            <Row>
              <Col span={24} style={{ textAlign: 'right', }}>
                <Space>
                  <Button type="defaulte" onClick={this.onCancel} >
                    取消
                  </Button>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    确定
                  </Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </Modal>
      </>


    );
  }
}
